package com.common.sdk.net.download;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;

import com.common.sdk.net.download.db.DownloadSQLiteOpenHelper;
import com.common.sdk.net.download.interfaces.IDownloadBuilder;
import com.common.sdk.net.download.util.DownloadFilePathUtils;
import com.common.sdk.net.download.util.DownloadLog;
import com.common.sdk.net.connect.http.HttpStack;
import com.common.sdk.net.connect.http.HurlStack;

/**
 * 下载线程初始化
 * @author wenlonglv
 *
 */
public class DownloadManger {
    private static Context context;

    public static Context getContext() {
        return context;
    }

    protected static void init(Context mContext) {
        context = mContext;
    }

    /**
     * 
     * @param mContext  必须是application
     * @return
     */
    protected static IDownloadBuilder newDownloadingDispatcher() {
        // 初始化SD卡路径
        long time1 = System.currentTimeMillis();
        DownloadFilePathUtils.initiateDirectory(context);
        long time2 = System.currentTimeMillis();
        DownloadLog.debug("downloadtime DownloadManger SD" + (time1 - time2));
        DownloadSQLiteOpenHelper.init(context);
        long time3 = System.currentTimeMillis();
        DownloadLog.debug("downloadtime DownloadManger SQLite" + (time2 - time3));

        // String userAgent = "sohu/sohuvideo";
        // try {
        // String packageName = context.getPackageName();
        // PackageInfo info =
        // context.getPackageManager().getPackageInfo(packageName, 0);
        // userAgent = packageName + "/" + info.versionCode;
        // } catch (NameNotFoundException e) {
        // DownloadLog.error(e);
        // }

        HttpStack stack = null;
        // if (stack == null) {
        // if (Build.VERSION.SDK_INT >= 9) {
        stack = new HurlStack();
        long time4 = System.currentTimeMillis();
        DownloadLog.debug("downloadtime DownloadManger HurlStack " + (time3 - time4));
        // } else {
        // stack = new
        // HttpClientStack(AndroidHttpClient.newInstance(userAgent));
        // }
        // }
        IDownloadBuilder queue = new DownloadQueue(stack);
        long time5 = System.currentTimeMillis();
        DownloadLog.debug("downloadtime DownloadManger new DownloadQueue" + (time4 - time5));
        queue.initialization();
        long time6 = System.currentTimeMillis();
        DownloadLog.debug("downloadtime DownloadManger DownloadQueue init" + (time5 - time6));
        return queue;
    }
}
